// 权限控制
import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import store from './store'
import { asyncRoutes } from '@/router/asyncRouters'

const WITHLIST = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/getUserInfo')
        const menus = res.roles.menus
        const filterRouters = asyncRoutes.filter(router => {
          return menus.includes(router.children[0].name)
        })
        router.addRoutes(filterRouters)
        store.commit('menu/setMenuList', filterRouters)
      }
    }
  } else {
    if (WITHLIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})
// 1.路由跳转权限控制
// 2.菜单权限控制
